<?php

namespace app\admin\controller;

use app\admin\model\XPotfpgoods;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 罐箱申请
 *
 */
class XPotsq extends Backend
{
    /**
     * XPotsq模型对象
     * @var \app\admin\model\XPotsq
     */
    protected $model = null;
    protected $fp= null;
    protected $good=null;
    protected $fpgood=null;
    protected $quickSearchField = ['TKID'];
    protected $noNeedLogin      = ['*'];
    protected $defaultSortField = 'TKID,desc';

    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XPotsq;
        $this->fp= new \app\admin\model\XPotfp();
        $this->good= new \app\admin\model\Goods();
        $this->fpgood =new XPotfpgoods();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $sy_type=$this->request->get('code');
        $sy_where='';
        $adminInfo          = $this->auth->getInfo();
        if($sy_type && $sy_type=='GXSQ'){
            $sy_where="tkid not in ( select tkid from x_potfp) and op='$adminInfo[nickname]'";
        }elseif($sy_type && $sy_type=='GXFP'){
            $sy_where="tkid not in ( select tkid from x_potfp)  and tjflag='1'";
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field("TKID,CORP,CONTYPE,dbo.f_get_potfpnum(TKID) as t,CONSUM,CONSIZE,TJFLAG,x_potsq.REMARK,x_potsq.OP,x_potsq.OPTIME,YWTYPE,codelib.codename")
//            ->field(" CORP,CONTYPE,CONSUM,CONSIZE,TJFLAG,REMARK,OP,OPTIME")
            ->join('codelib','x_potsq.CONTYPE=codelib.code')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where('codelib.CODETYPE','potkind')
            ->where($where)
            ->where($sy_where)
//            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['TKID']='TKSQ'.date('Ymdhis',time());
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']    =date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'),$this->model->TKID);
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 提交申请
     */
    public function tj(){
        $id=$this->request->get('TKID');
        $up=$this->model->where('TKID',$id)->save(['TJFLAG'=>1]);
        if($up){
            $this->success('提交成功');
        }else{
            $this->error('提交失败');
        }
    }
    /**
     * 查看罐箱分配列表
     */
    public function indexs()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with('fp')
            ->alias($alias)
            ->where($where)

            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * @throws \think\db\exception\DbException
     * 箱货匹配
     */
    public function index_good(){

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();

        $res = $this->model
            ->field('x_potsq.ID,x_potsq.TKID,x_potsq.CORP,x_potsq.YWTYPE,DEPARTMENT.DEPTNAME,codelib.codename,count(x_potfp.id) as count,CONSUM')
            ->join('DEPARTMENT',"x_potsq.DEPT=DEPARTMENT.DEPTID")
            ->join('x_potfp',"x_potsq.tkid=x_potfp.tkid")
            ->with('good')
            ->join('codelib','x_potsq.CONTYPE=codelib.code')
            ->where('codelib.CODETYPE','potkind')
//            ->with('fp')
            ->alias($alias)
            ->where($where)
            ->group('x_potsq.ID,x_potsq.TKID,x_potsq.CORP,x_potsq.YWTYPE,DEPARTMENT.DEPTNAME,codelib.codename,CONSUM')
            ->paginate($limit);

        $data=$res->toArray()['data'];
        $good= $this->good->column('GOODS','GOODSID');
        $a=[];
        foreach ($data as &$item) {
            if(!empty($item['good'])){
                foreach ($item['good'] as &$t) {
                    if(isset($good[$t['GOODSID']])){
                        $t['GOODSID']=$good[$t['GOODSID']];
                    }
                }
                $item['sum']=count(array_values(array_column( $item['good'], NULL, 'TCNO')));
//                foreach ($item['good'] as &$t) {
//                      $t['GOODSID']=$a[$t['TCNO']];
//
//                }
            }


        }
//        var_dump($data);die;
        $this->success('', [
            'list'   => $data,
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 货物箱号
     * TKID string 申请单id
     * CORP 公司简称
     * TYPE 1箱对货2货对箱
     */
    public function index_goodxq(){
        $get=$this->request->get();
        //查出申请单分配的箱号
//        $get['TKID']='TKSQ20201210143634';
//        $get['CORP']='壳牌化工';
//        $get['TYPE']=1;
        $tcno=$this->fp->where('TKID',$get['TKID'])->column('TCNO');
        //查出公司的货物
       $good=$this->good->where('CORP',$get['CORP'])->column('GOODSID,GOODS');
       //查出是否有已分类的商品
        $fp= $this->fpgood->where('TKID',$get['TKID'])->select()->toArray();
        $list=[];
        if($get['TYPE']==1){
            foreach ($fp as $item) {
                $list[$item['TCNO']][]=$item['GOODSID'];
            }
        }else{
            foreach ($fp as $item) {
                $list[$item['GOODSID']][]=$item['TCNO'];
            }
        }
       $this->success('',['box'=>$tcno,'good'=>$good,'fpgood'=>$list]);
    }

    /**
     * @throws \Exception
     * 箱货匹配
     */
    public function add_good(){
        $add=[];
        $adminInfo          = $this->auth->getInfo();
        $post=$this->request->post();
        $res=false;
        if(is_array($post['TCNO']) && is_array($post['GOODSID'])){
            foreach ($post['TCNO'] as $item) {
                foreach ($post['GOODSID'] as $go) {
                    $add['TKID']=$post['TKID'];
                    $add['TCNO']=$item;
                    $add['GOODSID']=$go;
                    $add['OP']=$adminInfo['nickname'];
                    $add['OPTIME']    =date('Y-m-d H:i:s',time());
                }
            }
            $res=$this->fpgood->saveAll($add);
        }elseif (is_array($post['TCNO']) && !is_array($post['GOODSID'])){

                foreach ($post['TCNO'] as $k=>$go) {
                    $add[$k]['TKID']=$post['TKID'];
                    $add[$k]['TCNO']=$go;
                    $add[$k]['GOODSID']=$post['GOODSID'];;
                    $add[$k]['OP']=$adminInfo['nickname'];
                    $add[$k]['OPTIME']    =date('Y-m-d H:i:s',time());
                }
            //删除原来的
            $this->fpgood->where(['TKID'=>$post['TKID'],'GOODSID'=>$post['GOODSID']])->delete();
            $res= $this->fpgood->saveAll($add);
        }elseif (!is_array($post['TCNO']) && is_array($post['GOODSID'])){
            foreach ($post['GOODSID'] as $k=>$go) {
                $add[$k]['TKID']=$post['TKID'];
                $add[$k]['TCNO']=$post['TCNO'];
                $add[$k]['GOODSID']=$go;;
                $add[$k]['OP']=$adminInfo['nickname'];
                $add[$k]['OPTIME']    =date('Y-m-d H:i:s',time());
            }
            //删除原来的
            $this->fpgood->where(['TKID'=>$post['TKID'],'TCNO'=>$post['TCNO']])->delete();

            $res= $this->fpgood->saveAll($add);
        }
        if($res){
            $this->success('添加成功');
        }else{
            $this->error('失败');
        }
    }
}